package mt.ctrl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import base.ctrl.BaseController;
import base.ctrl.BaseResult;
import base.jfinal.JsonUtil;
import base.jfinal.anatation.RouteBind;
import base.model.SessionModel;
import io.rong.ApiHttpClient;
import io.rong.models.FormatType;
import io.rong.models.SdkHttpResult;
import io.rong.models.TxtMessage;
import mt.Const;
import mt.business.Cache;
import mt.business.UserVO;
import mt.model.Order;
import mt.model.Pricetype;
import mt.model.Team;
import mt.model.TeamUser;
import mt.model.enums.OrderStatusEnum;
import mt.model.enums.PriceTypeEnum;

@RouteBind(path = "team")
public class TeamCtrl extends BaseController {

	public void getTeamList() {
		int shopId = ((SessionModel) this.getSessionAttr("SessionModel"))
				.getShopId();
		String strSql = "select teamid,teamname,nickname teamUsername,themename,t.startdate ,t.passdate,t.createdate,t.enddate,case when t.public=0 then '不公开' else '公开' end public from mt_team t left join mt_theme th on t.themeid=th.themeid left join mt_user u on t.teamUserId=u.userId where t.status=0 and th.shopId=?";
		List<Record> list = Db.find(strSql, shopId);
		this.renderJson(list);
	}

	// 获取我的队伍
	public void getMyTeam() {
		String code = getPara("code", "");
		int userId = Cache.GetUserVOByCode(code).getUserId();
		Map<String, Object> map = getParas();
		map.put("userId", userId + "");
		String strSql = "select distinct(mt.teamName),mtt.themeName,mt.headimgurl,mt.teamId";
		List<Record> list = Db.paginate(getParaToInt("page", 1),
				getParaToInt("pagesize", 10), strSql,
				getSql("team.getMyTeam", map)).getList();
		System.out.println((new JsonUtil(list)).toString());
		this.renderJson((new JsonUtil(list)).toString());
	}

	// 获取我可加入的队伍
	public void findTeam() {
		String code = getPara("code", "");
		int userId = Cache.GetUserVOByCode(code).getUserId();
		Map<String, Object> map = getParas();
		map.put("userId", userId + "");
		String strSql = "select mt.teamId,mtt.themeName,mt.teamName,mt.headimgurl";
		List<Record> list = Db.paginate(getParaToInt("page", 1),
				getParaToInt("pagesize", 10), strSql,
				getSql("team.findTeam", map)).getList();
		this.renderJson((new JsonUtil(list)).toString());
	}

	// 队伍信息
	public void findTeamUser() {
		String teamSql = "select mt.teamname,mtt.themename,mt.teamid,mtt.themeid from mt_team mt left join mt_theme mtt on mt.themeid=mtt.themeid where mt.teamid=?";
		Record teamInfo = Db.findFirst(teamSql, getPara("teamId", ""));
		JsonUtil ju = new JsonUtil(teamInfo.toJson());
		String teamUserSql = "select distinct mt.teamName,mtu.headimgurl,mtu.userName,mt.teamId,mtu.userid from mt_team mt,mt_user mtu,mt_team_user mttu where mt.teamId=mttu.teamId and mttu.userId=mtu.userId and mt.teamid=?";
		List<Record> teamUser = Db.find(teamUserSql, getPara("teamId", ""));
		ju.put("teamUser", teamUser);
		ju.put("teamUserSize", teamUser.size() + "");
		Record ticketCount = Db
				.findFirst(
						" select sum(quantity) ticketCount from mt_order mto where mto.teamid = ? and status = 1",
						getPara("teamId", ""));
		ju.put("ticket", ticketCount == null
				|| ticketCount.get("ticketCount") == null ? "0" : String
				.valueOf(ticketCount.get("ticketCount")));
		System.out.println(ju.toString());
		this.renderJson(ju.toString());
	}

	// 获取个人信息
	public void findUser() {
		String finduser = "select username,headimgurl from mt_user where userid=?";
		Record user = Db.findFirst(finduser, getPara("userId", ""));
		JsonUtil ju = new JsonUtil(user.toJson());
		System.out.println(ju.toString());
		this.renderJson(ju.toString());
	}

	// 修改队伍名字
	public void updateTeamName() {
		String teamname = getPara("teamname");
		String strsql = " update mt_team set teamname=? where teamid = ?";
		Db.update(strsql, teamname, getPara("teamid"));
		this.renderJson("{\"err\":0}");
	}

	// 添加队友
	public void addTeamUser() {
		List<Map<String, Object>> memberList = this.getParaToList("member");
		for (int i = 0; i < memberList.size(); i++) {
			Map<String, Object> itemMap = memberList.get(i);
			TeamUser teamUser = new TeamUser();
			teamUser.set("userId", itemMap.get("userid").toString());
			teamUser.set("teamId", getPara("teamId"));
			teamUser.save();
		}
		this.renderJson("{\"err\":0}");
	}

	// 获取app详情
	public void getTeamInfo() {

	}

	// 改方法给APP调用
	@Before(Tx.class)
	public void createTeam() {
		String code = getPara("code", "");
		int userId = Cache.GetUserVOByCode(code).getUserId();
		String username = Cache.GetUserVOByCode(code).getUserName();
		String teamName = "";
		String teamId = System.currentTimeMillis() + "";
		Team team = new Team();
		team.set("teamId", teamId);
		team.set("themeId", getParaToInt("themeId", 0));// 主题Id
		team.set("teamUserId", userId);// 队长Id
		team.set("createDate", (new java.text.SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss")).format(new Date()));
		List<Map<String, Object>> memberList = this.getParaToList("member");
		TeamUser teamUser1 = new TeamUser();
		teamUser1.set("userId", userId);
		teamUser1.set("teamId", teamId);
		teamUser1.save();
		teamName = username;
		List<String> userIds = new ArrayList<String>();
		for (int i = 0; i < memberList.size(); i++) {
			Map<String, Object> itemMap = memberList.get(i);
			TeamUser teamUser = new TeamUser();
			teamUser.set("userId", itemMap.get("userid").toString());
			teamUser.set("teamId", teamId);
			teamUser.save();
			userIds.add(Cache.GetUserVOById(
					Integer.parseInt(itemMap.get("userid").toString()))
					.getOpenId());
			teamName = teamName + "," + itemMap.get("username");
		}
		team.set("teamName", teamName);
		team.save();
		try {
			SdkHttpResult result = ApiHttpClient
					.createGroup(Const.IM_KEY, Const.IM_SECRET, userIds,
							teamId, teamName, FormatType.json);
			System.out.println("createGroup : " + result);

			result = ApiHttpClient.joinGroup(Const.IM_KEY, Const.IM_SECRET,
					Cache.GetUserVOByCode(code).getOpenId(), teamId, teamName,
					FormatType.json);
			System.out.println("joinGroup : " + result);

			result = ApiHttpClient
					.joinGroupBatch(Const.IM_KEY, Const.IM_SECRET, userIds,
							teamId, teamName, FormatType.json);
			System.out.println("joinGroupBatch : " + result);

			List<String> chatIds = new ArrayList<String>();
			chatIds.add(teamId);
			result = ApiHttpClient.publishGroupMessage(Const.IM_KEY,
					Const.IM_SECRET, Cache.GetUserVOByCode(code).getOpenId(),
					chatIds, new TxtMessage(username + "创建了队伍"), "", "",
					FormatType.json);
			System.out.println("publishGroupMessage=" + result);

			for (int i = 0; i < memberList.size(); i++) {
				Map<String, Object> itemMap = memberList.get(i);
				result = ApiHttpClient.publishGroupMessage(Const.IM_KEY,
						Const.IM_SECRET, Cache.GetUserVOById(
								Integer.parseInt(itemMap.get("userid")
										.toString())).getOpenId(), chatIds,
						new TxtMessage(itemMap.get("username") + "加入了队伍"), "",
						"", FormatType.json);
				System.out.println("publishGroupMessage=" + result);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		this.renderJson("{\"err\":0,teamId:\"" + teamId + "\"}");
	}

	// 改方法给APP调用
	public void joinTeam() {
		TeamUser teamUser = new TeamUser();
		teamUser.set("teamId", getPara("teamId"));
		teamUser.set("userId", getPara("userId"));
		teamUser.save();
		SdkHttpResult result = null;
		try {
			result = ApiHttpClient.joinGroup(Const.IM_KEY, Const.IM_SECRET,
					Cache.GetUserVOByCode(getPara("userId")).getOpenId(),
					getPara("teamId"), null, FormatType.json);
			System.out.println("joinGroup : " + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.renderJson("{\"err\":0}");
	}

	// 更新队伍信息
	public void updateTeam() {

	}

	// 退出队伍
	public void quitTeam() {
		// todo 判断是否有订单
		Db.update("delete from mt_team_user where teamId = ? and userId = ?",
				getPara("teamId", ""), getPara("userId", ""));
		this.renderJson("{\"err\":0}");
	}

	// 申请入场
	public void entrance() {
		BaseResult<Object> result = new BaseResult<Object>(false);
		String code = getPara("code", "");
		String teamId = getPara("teamId", "");
		UserVO user = Cache.GetUserVOByCode(code);
		if (user == null || StringUtils.isBlank(teamId)) {
			log.error("操作失败，参数错误，请确认是否已登录！");
			result.setMessage("操作失败，参数错误，请确认是否已登录！");
			renderJson(result.toJsonString());
			return;
		}

		// 判断是不是队长
		Team team = Team.dao.findFirst(
				"select * from mt_team where teamId = ?", teamId);
		if (user.getUserId() != Integer.valueOf(team.getStr("teamUserId"))) {
			log.error("操作失败，非队伍队长，无权申请入场！");
			result.setMessage("操作失败，无权进行此操作！");
			renderJson(result.toJsonString());
			return;
		}

		String teamSql = "select mt.teamid,mt.teamname,mtt.themename,mtt.themeId,mtt.price,mtt.priceType,mtt.minimum from mt_team mt left join mt_theme mtt on mt.themeid=mtt.themeid where mt.teamid=?";
		Record teamInfo = Db.findFirst(teamSql, teamId);
		int themeId = teamInfo.getInt("themeId");

		// 判断订单金额
		Number totalMoney = Db
				.queryNumber(
						"select sum(money) totalMoney from mt_order where status = 1 and teamId = ? and themeId = ?",
						teamId, themeId);
		if (totalMoney == null || totalMoney.longValue() <= 0) {
			log.error("操作失败，钱还不够！");
			result.setMessage("操作失败，钱还不够！");
			renderJson(result.toJsonString());
			return;
		}

		if (teamInfo.getInt("priceType") == PriceTypeEnum.PER_TICKET.getCode()) {
			if (totalMoney.longValue() >= teamInfo.getBigDecimal("price")
					.longValue()
					* teamInfo.getInt("minimum")) {
				renderJson(result.setSuccess(true).setMessage("OK").setData(
						true).toJsonString());
				return;
			} else {
				result.setMessage("操作失败，钱还不够！");
				renderJson(result.toJsonString());
				return;
			}
		}

		// 包场
		Number teamMemberCount = Db.queryNumber(
				"select count(id) num from mt_team_user where teamId = ?",
				teamId);
		Pricetype rate = Pricetype.dao.findFirst(
				"select * from mt_theme_rate where themeId= ? and minPlayer < ? and type="
						+ PriceTypeEnum.BOOKING.getCode(), themeId,
				teamMemberCount);
		if (rate == null
				|| totalMoney.longValue() < rate.getBigDecimal("price")
						.longValue()) {
			log.error("操作失败，钱还不够！");
			result.setMessage("操作失败，钱还不够！");
			renderJson(result.toJsonString());
			return;
		}

		renderJson(result.setSuccess(true).setMessage("OK").setData(true)
				.toJsonString());
	}

	// 解散队伍
	public void dismissTeam() {

		// 参数
		BaseResult<Object> result = new BaseResult<Object>(false);
		String code = getPara("code", "");
		String teamId = getPara("teamId", "");
		UserVO user = Cache.GetUserVOByCode(code);
		if (user == null || StringUtils.isBlank(teamId)) {
			log.error("操作失败，参数错误，请确认是否已登录！");
			result.setMessage("操作失败，参数错误，请确认是否已登录！");
			renderJson(result.toJsonString());
			return;
		}

		// 查询队伍
		Team team = Team.dao.findFirst(
				"select * from mt_team where teamId = ?", teamId);
		if (user.getUserId() != Integer.valueOf(team.getStr("teamUserId"))) {
			log.error("操作失败，非队伍队长，无权解散队伍！");
			result.setMessage("操作失败，无权进行此操作！");
			renderJson(result.toJsonString());
			return;
		}

		boolean isExistPayment = false;
		boolean isThemeStarted = team.getDate("startDate") != null;
		List<Order> orders = Order.dao.find(
				"select * from mt_order where teamId = ? ", teamId);
		if (orders == null || orders.isEmpty() || isThemeStarted) {// 没有支付信息
			Db.update("delete from mt_team where teamId = ? ", getPara(
					"teamId", ""));// 直接删除队伍数据
			Db.update("delete from mt_team_user where teamId = ? ", getPara(
					"teamId", ""));// 删除队伍成员
		} else {
			Db.update("update from mt_team set status=1 where teamId = ? ",
					teamId);// 修改队伍状态为
			if (!isThemeStarted) {
				// 还没入场的，则处理相关订单
				boolean refundProcess = true;
				for (Order order : orders) {
					if (!refundProcess) {
						log.error("解散队伍，操作失败，订单处理异常！");
						renderJson(result.setMessage("操作失败，订单处理异常！"));
						return;
					}
					OrderStatusEnum orderStatus = OrderStatusEnum
							.getEnumByCode(order.getInt("status"));
					switch (orderStatus) {
					case PAY_SUCCESS:
						// 有组员已经支付了,退款操作
						refundProcess &= order.set("status",
								OrderStatusEnum.FUND_APPLY.getCode()).set(
								"memo", "队伍解散退款！").update();
						isExistPayment = true;
						break;
					case WAIT_PAY:
					case TIMEOUT:
						// 修改订单状态
						refundProcess &= order.set("status",
								orderStatus.getCode()).update();
					default:
						break;
					}
				}
			}
		}

		try {
			List<String> toIds = new ArrayList<String>();
			toIds.add(teamId);
			SdkHttpResult imResult = ApiHttpClient.dismissGroup(Const.IM_KEY,
					Const.IM_SECRET, Cache.GetUserVOByCode(code).getOpenId(),
					getPara("teamId"), FormatType.json);
			log.info("dismissGroup in im, result=" + imResult);
		} catch (Exception e) {
			log.error("dismissGroup in im exception", e);
		} finally {
			// 当前解散队伍是否已经入场。
			String tipMsg = !isThemeStarted && isExistPayment ? "操作成功，订单24小时内退款，敬请关注！"
					: "操作成功";
			renderJson(result.setSuccess(true).setMessage(tipMsg)
					.toJsonString());
		}

	}

}